package com.example.javawebdemo.dao;
// ProductDAOImpl.java (原ProductDAO改造为具体类)

import com.example.javawebdemo.jdbc.JDBCTemplateSingleton;
import com.example.javawebdemo.models.Product;
import org.springframework.jdbc.core.RowMapper;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;

public class ProductDAOImpl implements ProductDAO {
    // 原ProductDAO方法实现移入此处
    // 添加静态行映射器
    private static final RowMapper<Product> PRODUCT_ROW_MAPPER = (rs, rowNum) -> {
        Product product = new Product();
        product.setId(rs.getInt("id"));
        product.setName(rs.getString("name"));
        product.setPrice(rs.getDouble("price"));
        product.setStock(rs.getInt("stock"));
        product.setDescription(rs.getString("description"));
        product.setImageUrl(rs.getString("image_url"));
        product.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
        return product;
    };
    @Override
    public List<Product> getAllProducts() throws SQLException {
        return JDBCTemplateSingleton.getJdbcTemplate().query(
                "SELECT id, name, price, stock, description, image_url, created_at FROM products",
                PRODUCT_ROW_MAPPER);
    }

    @Override
    public Product getProductById(int id) throws SQLException {
        try {
            return JDBCTemplateSingleton.getJdbcTemplate().queryForObject(
                    "SELECT * FROM products WHERE id = ?",
                    PRODUCT_ROW_MAPPER, id);
        } catch (Exception e) {
            return null; // 查询无结果时返回null
        }
    }
    @Override
    public boolean addProduct(Product product) throws SQLException {
        String sql = "INSERT INTO products (name, price, stock, description, image_url, created_at) " +
                "VALUES (?, ?, ?, ?, ?, ?)";
        return JDBCTemplateSingleton.getJdbcTemplate().update(sql,
                product.getName(),
                product.getPrice(),
                product.getStock(),
                product.getDescription(),
                product.getImageUrl(),
                LocalDateTime.now()) > 0;
    }

    @Override
    public boolean updateProduct(Product product) throws SQLException {
        String sql = "UPDATE products SET name=?, price=?, stock=?, description=?, image_url=? " +
                "WHERE id=?";
        return JDBCTemplateSingleton.getJdbcTemplate().update(sql,
                product.getName(),
                product.getPrice(),
                product.getStock(),
                product.getDescription(),
                product.getImageUrl(),
                product.getId()) > 0;
    }

    @Override
    public boolean deleteProduct(int id) throws SQLException {
        return JDBCTemplateSingleton.getJdbcTemplate().update(
                "DELETE FROM products WHERE id = ?", id) > 0;
    }

}
